import javax.servlet.http.HttpServletRequest;
import grails.util.GrailsWebUtil;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.web.context.request.RequestContextHolder;
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class StitchesSearchResultTagLib {
    private static final String ENTITY_AMPERSAND = "&";
    static namespace = 'stitches'

    private void appendRequestParams(StringBuffer actualUriBuf, Map params, HttpServletRequest request) {


        boolean querySeparator = false;

        for (Iterator i = params.keySet().iterator(); i.hasNext();) {
            Object name = i.next();
            //if(name.equals(GrailsControllerClass.CONTROLLER) || name.equals(GrailsControllerClass.ACTION) || name.equals(ARGUMENT_ID))
             //   continue;

            if(!querySeparator) {
                    actualUriBuf.append('?');
                    querySeparator = true;
            }
            else {
                actualUriBuf.append(ENTITY_AMPERSAND);
            }
            Object value = params.get(name);
            appendRequestParam(actualUriBuf, name, value,request);

        }
    }

    private String urlEncode(Object obj, ServletRequest request) {
        try {
            String charset = request.getCharacterEncoding();
            
            return URLEncoder.encode(obj.toString(), (charset != null) ? charset : GrailsWebUtil.DEFAULT_ENCODING );
        } catch (UnsupportedEncodingException ex) {
            throw new ControllerExecutionException("Error creating URL, cannot URLEncode to the client's character encoding: "+ ex.getMessage(),ex);
        }
    }

    
    
    /*
     * Appends a request parameters for the given aname and value
     */
    private void appendRequestParam(StringBuffer actualUriBuf, Object name, Object value, HttpServletRequest request) {
        if (value==null)
            value = "";

        actualUriBuf.append(urlEncode(name, request))
                 .append('=')
                 .append(urlEncode(value, request));
    }   
    
    def createLinkToStitch = { attrs ->
    def writer = out
    def urlAttrs = attrs
    def url

    def params = urlAttrs.params && urlAttrs.params instanceof Map ? urlAttrs.remove('params') : [:]
    StringBuffer actualUriBuf = new StringBuffer()
    actualUriBuf.append(ConfigurationHolder.config.stitches.server)
    actualUriBuf.append('/viewContent/view')
    
    params.remove('base')
    
    def searchResult = params.get('searchResult')
    
    params.remove('searchResult')
    
    
    
    params.put('contentVersionId',searchResult.contentVersionId)
    		
    params.put('viewSecureToken',searchResult.viewSecureToken)
    
    appendRequestParams(actualUriBuf,params,request)
    url = actualUriBuf.toString()
    println("url=" + url)
    if (response == null) 
    	println("response isnull")
    out << response.encodeURL(url)
    
    }
    def createLinkToStitch2 = { attrs ->

        def searchResult = attrs["searchResult"]

        
//<img src="<g:createLink action="view" params="[width:'23',contentVersionId:attributeValueBlobInstance.contentVersion.id,attributename:attributeValueBlobInstance.attribute.name,viewsecuretoken:attributeValueBlobInstance.contentVersion.content.viewSecureToken]"/>">

        switch (a.status) {
        case S3Asset.STATUS_NEW:
        case S3Asset.STATUS_INPROGRESS:
            out << grailsAttributes.getApplicationUri(request) + a.localUrl
            break
        case S3Asset.STATUS_HOSTED:
            out << a.url()
            break
        case S3Asset.STATUS_REMOVED:
        case S3Asset.STATUS_BLANK:
            // TODO: must get a "not found" image for this
            break
        }
    }
}